// pages/evaluate-submit/evaluate-submit.js
const app = getApp()
Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    coach: {},
    currentRating: 0,
    content: '',
    userInfo: null
  },

  onLoad(options) {
    const coachId = options.coach_id
    this.getCoachInfo(coachId)
    this.checkLogin()
  },

  // 获取教练信息
  getCoachInfo(coachId) {
    wx.request({
      url: `${this.data.backendUrl}get_coach_detail.php`,
      data: { id: coachId },
      success: res => {
        if (res.data.status === 'success') {
          this.setData({ coach: res.data.coach })
        }
      }
    })
  },

  // 检查登录状态
  checkLogin() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({ title: '请先登录', icon: 'none' })
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' })
      }, 1500)
      return
    }
    this.setData({ userInfo })
  },

  // 处理评分
  handleRating(e) {
    const rating = e.currentTarget.dataset.rating
    this.setData({ currentRating: rating })
  },

  // 处理评论输入
  handleComment(e) {
    this.setData({ content: e.detail.value })
  },

  // 提交评价
  async handleSubmit() {
    const { currentRating, content, userInfo, coach } = this.data
    
    // 验证评分
    if (currentRating === 0) {
      wx.showToast({ title: '请选择评分', icon: 'none' })
      return
    }

    // 验证预约记录
    const canSubmit = await this.checkBooking()
    if (!canSubmit) {
      wx.showToast({ 
        title: '未预约过该教练，无法评价', 
        icon: 'none',
        duration: 2000
      })
      return
    }

    // 提交数据
    wx.request({
      url: `${this.data.backendUrl}submit_evaluate.php`,
      method: 'POST',
      data: {
        user_id: userInfo.id,
        coach_id: coach.id,
        rating: currentRating,
        content: content
      },
      success: res => {
        if (res.data.status === 'success') {
          wx.showToast({ title: '评价成功' })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          console.log(this.data)
          wx.showToast({ title: '提交失败', icon: 'none' })
        }
      }
    })
  },

  // 检查预约记录
  checkBooking() {
    return new Promise((resolve) => {
      wx.request({
        url: `${this.data.backendUrl}check_booking.php`,
        data: {
          user_id: this.data.userInfo.id,
          coach_id: this.data.coach.id
        },
        success: res => {
          resolve(res.data.hasBooking)
        }
      })
    })
  }
})